package mo.org.cm309.shoppingcart.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mo.org.cm309.shoppingcart.entity.Cart;
import mo.org.cm309.shoppingcart.service.ProductService;

public class AddToCartServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try{
			String id 		= req.getParameter("productId");
			String qty		= req.getParameter("quantity");
			long productId  = Long.parseLong(id);
			int quantity	= Integer.parseInt(qty);
			ProductService productService = new ProductService();
			Cart cart 		= (Cart)req.getSession().getAttribute("cart");
			cart 			= productService.addToCart(cart, productId, quantity);
			req.getSession().setAttribute("cart", cart);
			resp.sendRedirect("showCartServlet");
		}catch(NumberFormatException e){
			PrintWriter writer = resp.getWriter();
			writer.print("<html>");
			writer.print("Error 404 : Product Not Found !");
			writer.print("</html>");
		}
		
	}
}
